package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.enums.CsPlatformType;
import com.ruoyi.common.utils.SnowflakeIdGenerator;
import com.ruoyi.system.domain.CsInventory;
import com.ruoyi.system.domain.CsSalesRecord;
import com.ruoyi.system.mapper.CsInventoryMapper;
import com.ruoyi.system.mapper.CsSalesRecordMapper;
import com.ruoyi.system.service.ICsSalesRecordService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import static com.ruoyi.common.utils.ShiroUtils.getUserId;

/**
 * 出售记录Service业务层处理
 *
 * @author ruoyi
 * @date 2025-10-05
 */
@Service
public class CsSalesRecordServiceImpl extends ServiceImpl<CsSalesRecordMapper, CsSalesRecord> implements ICsSalesRecordService {
    @Autowired
    private CsSalesRecordMapper csSalesRecordMapper;
    @Autowired
    private CsInventoryMapper csInventoryMapper;
    @Autowired
    private SnowflakeIdGenerator snowflakeIdGenerator;
    @Autowired
    private CsInventoryServiceImpl csInventoryServiceImpl;

    /**
     * 查询出售记录
     *
     * @param id 出售记录主键
     * @return 出售记录
     */
    @Override
    public CsSalesRecord selectCsSalesRecordById(Long id) {
        return csSalesRecordMapper.selectById(id);
    }

    /**
     * 查询出售记录列表
     *
     * @param csSalesRecord 出售记录
     * @return 出售记录
     */
    @Override
    public List<CsSalesRecord> selectCsSalesRecordList(CsSalesRecord csSalesRecord) {
        return csSalesRecordMapper.selectList(new LambdaQueryWrapper<CsSalesRecord>()
                .eq(CsSalesRecord::getUserId, getUserId())
                .eq(!ObjectUtils.isEmpty(csSalesRecord.getAccount()), CsSalesRecord::getAccount, csSalesRecord.getAccount())
                .eq(!ObjectUtils.isEmpty(csSalesRecord.getPlatform()), CsSalesRecord::getPlatform, csSalesRecord.getPlatform())
                .like(!ObjectUtils.isEmpty(csSalesRecord.getName()), CsSalesRecord::getName, csSalesRecord.getName())
                .orderByDesc(CsSalesRecord::getId));
    }


    /**
     * 新增出售记录
     *
     * @param csSalesRecord 出售记录
     * @return 结果
     */
    @Override
    @Transactional
    public int insertCsSalesRecord(CsSalesRecord csSalesRecord) {
        Long userId = getUserId();
        CsInventory csInventory = csInventoryMapper.selectOne(new LambdaQueryWrapper<CsInventory>()
                .eq(CsInventory::getMarketHashName, csSalesRecord.getMarketHashName())
                .eq(CsInventory::getUserId, userId)
                .eq(CsInventory::getAccount, csSalesRecord.getAccount()));
        if (csInventory == null) {
            throw new RuntimeException(String.format("账户 %s 库存中，没有此物品 %s", csSalesRecord.getAccount(), csSalesRecord.getMarketHashName()));
        }
        csInventory.setQuantity(csInventory.getQuantity() - csSalesRecord.getQuantity());
        csInventory.setAvailableQuantity(csInventory.getAvailableQuantity() - csSalesRecord.getQuantity());
        if (csSalesRecord.getId() == null) {
            csSalesRecord.setId(snowflakeIdGenerator.nextId());
            csSalesRecord.setUserId(getUserId());
        }
        csSalesRecord.setName(csInventory.getName());
        csSalesRecord.setSellCostPrice(csInventory.getUnitCost());
        Long sellPrice = csSalesRecord.getSellPrice();
        if (csSalesRecord.getPlatform().equals(String.valueOf(CsPlatformType.STEAM.val()))) {
            sellPrice = BigDecimal.valueOf(csSalesRecord.getSellPrice())
                    .divide(BigDecimal.valueOf(100))
                    .setScale(2, RoundingMode.DOWN)
                    .multiply(BigDecimal.valueOf(0.87))
                    .setScale(2, RoundingMode.DOWN)
                    .multiply(BigDecimal.valueOf(0.8))
                    .setScale(2, RoundingMode.DOWN)
                    .multiply(BigDecimal.valueOf(100)).longValue();
        }
        csSalesRecord.setTotalProfit((sellPrice - csInventory.getUnitCost()) * csSalesRecord.getQuantity());
        csInventory.setHistoryProfit(csInventory.getHistoryProfit() + csSalesRecord.getTotalProfit());
        if (csInventory.getQuantity() <= 0) {
            csInventory.setUnitCost(0L);
        }
        csInventoryMapper.updateById(csInventory);
        return csSalesRecordMapper.upsetSalesRecord(csSalesRecord);
    }

    /**
     * 修改出售记录
     *
     * @param newSalesRecord 出售记录
     * @return 结果
     */
    @Override
    @Transactional
    public int updateCsSalesRecord(CsSalesRecord newSalesRecord) {
        CsSalesRecord oldSalesRecord = csSalesRecordMapper.selectById(newSalesRecord.getId());
        if (newSalesRecord.getPlatform().equals(String.valueOf(CsPlatformType.STEAM.val()))) {
            newSalesRecord.setTotalProfit((long) ((newSalesRecord.getSellPrice() * 0.8) - newSalesRecord.getSellCostPrice()) * newSalesRecord.getQuantity());
        } else {
            newSalesRecord.setTotalProfit((long) (newSalesRecord.getSellPrice() - newSalesRecord.getSellCostPrice()) * newSalesRecord.getQuantity());
        }
        if (oldSalesRecord.getMarketHashName().equals(newSalesRecord.getMarketHashName())) {
            // 没有修改原本物品名称
            csInventoryServiceImpl.updateInventoryByOldSalesRecord(newSalesRecord, oldSalesRecord);
            csSalesRecordMapper.updateById(newSalesRecord);
        } else {
            // 修改了原本物品信息 给库存管理加数量  减去总盈利
            csInventoryMapper.update(null, new LambdaUpdateWrapper<CsInventory>()
                    .eq(CsInventory::getMarketHashName, oldSalesRecord.getMarketHashName())
                    .setSql("quantity = quantity + " + oldSalesRecord.getQuantity())
                    .setSql("available_quantity = available_quantity + " + oldSalesRecord.getQuantity())
                    .setSql("history_profit = history_profit - " + oldSalesRecord.getTotalProfit()));
            // 修改新的物品信息
            insertCsSalesRecord(newSalesRecord);
        }
        return 1;
    }

    /**
     * 批量删除出售记录
     *
     * @param ids 需要删除的出售记录主键
     * @return 结果
     */
    @Override
    public int deleteCsSalesRecordByIds(String ids) {
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(Long::parseLong)
                .collect(Collectors.toList());
        return csSalesRecordMapper.deleteBatchIds(idList);
    }

    /**
     * 删除出售记录信息
     *
     * @param id 出售记录主键
     * @return 结果
     */
    @Override
    public int deleteCsSalesRecordById(Long id) {
        return csSalesRecordMapper.deleteById(id);
    }
}
